<?php

namespace app\api\controller;

/**
 * 预约控制器
 * Class Appointment
 * @package app\api\controller
 */

use app\api\model\WxMessage;
use app\common\enum\AppointmentStatus;
use app\common\model\AppointmentOrder;
use app\common\model\AppointmentOrder as AppointmentOrderModel;
use app\api\model\Order as OrderModel;
use app\api\model\OrderGoods as OrderGoodsModel;
use app\api\model\GoodsSku as GoodsSkuModel;
use app\api\model\sharing\OrderGoods as sharingOrderGoodsModel;
use app\common\model\AppointmentRecord;
use app\common\model\AppointmentService as ServiceModel;
use app\common\service\Order as OrderService;
use app\api\model\appointment\Time as TimeModel;
use app\api\model\appointment\Type as TypeModel;
use think\Db;
use app\api\model\Goods;
use app\common\model\CommentImage;
use think\Model;

class Appointment extends Controller
{
    /* @var \app\api\model\User $user */
    private $user;

    /**
     * 构造方法
     * @throws \app\common\exception\BaseException
     * @throws \think\exception\DbException
     */
    public function _initialize()
    {
        parent::_initialize();
        // 用户信息
        $this->user = $this->getUser();
    }

    /*
     * 线下订单详情
     */
    public function offlineOrder()
    {
        $order_id = input('order_id');
        $orderModel = new AppointmentOrderModel;
        $detail = $orderModel->offlineDetail($order_id);
        return $this->renderSuccess(compact('detail'));
    }

    /**
     * 预约列表
     */
    public function page_list()
    {
        $orderModel = new AppointmentOrderModel;
        $list = $orderModel->lists($this->user['user_id']);
        return $this->renderSuccess(compact('list'));
    }

    /**
     * 预约页面信息
     */
    public function page_data()
    {
        //订单id
        $order_id = input('order_id');
        if (empty($order_id)) $this->renderError('订单信息非法');

        //商品id
        $goods_id = input('goods_id');
        if (empty($goods_id)) $this->renderError('商品信息非法');

        //商品规格
        $sku_id = input('sku_id');
        if (empty($sku_id)) $this->renderError('商品规格信息非法');

        $sku = $this->getGoodsType($order_id, $goods_id, $sku_id);
        if (empty($sku)) return $this->renderError('未找到预约类型');

        $orderModel = new AppointmentOrderModel;
        $state = $orderModel->isUse($this->user['user_id'], $order_id, $goods_id, $sku_id);
        if (!$state) {
            return $this->renderError($orderModel->getError());
        }

        //预约日期
        $date = input('date', date('Y-m-d', time()));
        $list = $orderModel->getStateByDate($date, $sku['type_id']);

        $user = $this->getUser();
        if (empty($user['address_default'])) {
            $address = '';
        } else {
            $address = $user['address_default'];
            $address['address'] = $address['region']['province'] . $address['region']['city'] . $address['region']['region'] . $address['detail'];
        }

        $card_info = $orderModel->cardInfo($this->user['user_id'], $order_id, $goods_id, $sku_id);

        if ($list === false) return $this->renderError('列表数据为空');

        return $this->renderSuccess(compact('list', 'address', 'card_info'));
    }

    /**
     * 提交预约信息
     */
    public function page_submit()
    {
        //订单id
        $order_id = input('order_id');
        if (empty($order_id)) $this->renderError('订单信息非法');

        //商品id
        $goods_id = input('goods_id');
        if (empty($goods_id)) $this->renderError('商品信息非法');

        //商品规格
        $sku_id = input('sku_id');
        if (empty($sku_id)) $this->renderError('商品规格信息非法');

        //客户姓名
        $user_name = input('user_name');
        if (empty($user_name)) $this->renderError('名称不能为空');

        //客户联系方式
        $user_phone = input('user_phone');
        if (empty($user_phone)) $this->renderError('联系方式不能为空');

        //客户服务地址
        $address = input('address');
        if (empty($address)) $this->renderError('服务地址不能为空');

        //预约日期
        $date = input('appointment_date');
        if (empty($date)) $this->renderError('未选择日期');

        $time_id = input('time_id');
        if (empty($time_id)) $this->renderError('未选择时间段');

        $sku = $this->getGoodsType($order_id, $goods_id, $sku_id);
        if (empty($sku)) return $this->renderError('未找到预约类型');
        //判断是否可以预约
        $orderModel = new AppointmentOrderModel;
        $state = $orderModel->isOk($sku['type_id'], $date, $time_id, $order_id, $goods_id);
        if (!$state) {
            return $this->renderError($orderModel->getError());
        }
        if(isset($sku['goods_sku_name'])){
            $offline_name = $sku['goods_sku_name'];
        }else{
            $offline_name = $sku['goods_name'];
        }
        //订单中的备注赋值给预约订单并支持后台修改
        $appint = new OrderModel();
        $order = $appint->where(['order_id' => $order_id])->find();
        $remark = $order['buyer_remark'];
        $data = [
            'user_id' => $this->user['user_id'],
            'type_id' => $sku['type_id'],
            'appointment_date' => $date,
            'user_name' => $user_name,
            'user_phone' => $user_phone,
            'offline_name' => $offline_name,
            'address' => $address,
            'time_id' => $time_id,
            'user_order_id' => $order_id,
            'user_goods_id' => $goods_id,
            'user_goods_sku' => $sku_id,
            'num' => $sku['total_num'],
            'order_desc'=>$remark
        ];

        $result = $orderModel->add($data);
        $order_id = $orderModel->getLastInsID();
        log_print($order_id);
        if (!$result) return $this->renderError($orderModel->getError());
        $day = $data['appointment_date'];
        $time = Db::name('appointment_time')->where('time_id', $data['time_id'])->value('name');
        $message = [
            'openid' => $this->user['open_id'],
            'name' => Db::name('appointment_type')->where('type_id', $sku['type_id'])->value('name'),
            'time' => $day . ' ' . '' . '' . '' . $time
        ];
       $order->save(['order_status'=>40]);
        //推送预约信息
        WxMessage::sendMessage(1, $message);
        AppointmentRecord::addRecord($order_id,$this->user['nickName'],1);
        return $this->renderSuccess([], '预约成功');
    }

    public function getGoodsInfo(){
        $order_id = input('order_id');
        if(empty($order_id) == true){
            return $this->renderError('未找到订单');
        }
        $appint = new AppointmentOrderModel();
        $order = $appint->where(['id' => $order_id])->find();
        $sku = Goods::detail($order['user_goods_id']);
        return $sku;
    }

    private function getGoodsType($order_id, $goods_id, $sku_id)
    {
        $order = OrderModel::detail(['order_id' => $order_id]);
        //$order =Db::name('appointment_order')->where('id', $order_id)->find();
        if ($order) {
            $sku = OrderGoodsModel::detail(['order_id' => $order_id, 'goods_id' => $goods_id]);
            //$sku = Db::name('appointment_order')->where('id', $order_id)->find();
            if (empty($sku)) return $this->renderError('未找到预约类型');
            $goodsSkuModel = new GoodsSkuModel();
            if ($sku['goods_type'] == 3) {
                $sku = Db::name('goods_sku_copy')->where('goods_id', $goods_id)
//                    ->where("find_in_set(goods_sku_id,'" . $sku['goods_sku_ids'] . "')")
                        ->where('goods_sku_id',$sku_id)
                    ->find();
            } else {
                if ($sku['goods_sku_id'] != $sku_id) {
                    return false;
                }
            }
        } else {
            $sku = sharingOrderGoodsModel::detail(['order_id' => $order_id, 'goods_id' => $goods_id, 'goods_sku_id' => $sku_id]);
        }

        return $sku;
    }

    /**
     * 预约记录
     */
    public function log()
    {
        $oder_id = input('order_id');
        if (empty($oder_id)) return $this->renderError("订单号不能为空");
        //获取当前订单类型

        $order = OrderModel::detail(['order_id' => $oder_id]);
        $orderModel = new AppointmentOrderModel;
        $list = false;

        if ($order) {
            $OrderGoodsModel = new OrderGoodsModel();
            $appointment_type = $OrderGoodsModel->getOrderType($oder_id);

            switch ($appointment_type) {
                case 6:
                case 0:
                    $list = $orderModel->goodsDetail($oder_id);
                    break;
                case 1:
                    $list = $orderModel->timeDetail($oder_id);
                    break;
                case 2:
                    $list = $orderModel->monthDetail($oder_id);
                    break;
                case 3:
                    $list = $orderModel->packetDetail($oder_id);
                    break;
                case 4:
                    $list = $orderModel->goodsYsDetail($oder_id);
                    break;
            }
        } else {
            $appointment_type = 0;
            $list = $orderModel->sharingDetail($oder_id);
        }

        if ($list === false) return $this->renderError('列表数据为空');

        return $this->renderSuccess([
            'appointment_type' => $appointment_type,
            'list' => $list,
        ]);
    }

    /**
     * 订单确认完成
     * @return array
     */
    public function confirm_finish()
    {
        $oder_id = input('order_id');
        if (empty($oder_id)) return $this->renderError("订单号不能为空");

        $serviceModel = new ServiceModel;

        $status = $serviceModel->confirm_finish($oder_id);
        if ($status) return $this->renderSuccess([], 'success');

        return $this->renderError($serviceModel->getError());
    }
    /**
     * YPP评价完成
     * @return array
     */
    public function ping_finish()
    {
        $stars = input('stars');
        $ping = input('ping');
        if($ping=='undefined'){
            $ping = '';
        }else{
            $ping = $ping?$ping:"";
        }
        $order_id = input('order_id');
        $img_ids = input('img_ids');
        $app_order = Db::name('appointment_order')->where('id', $order_id)->find();

        $order_goods =  Db::name('order_goods')->where('order_id', $app_order['user_order_id'])->find();
        $img = 0;
        if($img_ids){
            $img = 1;
        }
        $status = Db::name('appointment_order')->where('id', $order_id)
            ->update([
                'stars' => $stars,
                'ping' => $ping,
                'is_img'=>$img,
                'ping_img'=>$img_ids
            ]);
        $score = 20;
        if($stars==5){
            $score = 10;
        }
        if($stars==1){
            $score = 30;
        }
       $commentid =  Db::name('comment')
            ->insertGetId([
                'score' => $score,
                'stars'=>$stars,
                'content' => $ping,
                'ping_img'=>$img_ids,
                'is_picture' => $img,
                'sort' => 100,
                'status' => 1,
                'user_id' => $this->user['user_id'],
                'order_id' => $app_order['id'],
                'goods_id' => $order_goods['goods_id'],
                'order_goods_id' => $order_goods['order_goods_id'],
                'wxapp_id' => $order_goods['wxapp_id'],
                'is_delete' => 0,
                'create_time' => time(),
                'update_time' => time(),
            ]);
        if($img == 1){
            $image = explode(',',$img_ids);
            foreach($image as $key => $val){
                $imageData[] = [
                    'comment_id' => $commentid,
                    'image_id' => $val,
                    'wxapp_id' => $order_goods['wxapp_id']
                ];
            }
            $model = new CommentImage;
           $model->saveAll($imageData);
        }
        if ($status) return $this->renderSuccess([], 'success');

        return $this->renderError([], 'error');
    }
    public function add_data()
    {
        $list = Db("appointment_order")->select();

        $service_db = Db("appointment_service");
        foreach ($list as $v) {
            $exist = $service_db->where('order_id', $v['order_id'])->find();
            if (!$exist) {
                $service_db->insert([
                    'order_id' => $v['id'],
                    'service_id' => $v['service_id'],
                    'price' => 100,
                    'service_price' => 50,
                    'wxapp_id' => $v['wxapp_id'],
                    'create_time' => time(),
                    'update_time' => time(),
                ]);
            }
        }
    }


    /*
     * 师傅添加线下订单信息
     */
    public function offlineInfo()
    {
        $order_id = OrderService::createOrderNo();

        $status_list = AppointmentStatus::data();

        $timeModel = new TimeModel;
        $time_list = $timeModel->getList();

        $typeModel = new TypeModel;
        $type_list = $typeModel->getList();

        return $this->renderSuccess(compact('order_id', 'status_list', 'time_list','type_list'));
    }

    /*
       * 根据类型获取时间列表
     */
    public function getTimeList()
    {
        $type_id = input('type_id',1);
        $date_id = input('date_id');
        $date = strtotime($date_id);

        $list = TimeModel::useTimeList($type_id,$date);
        return $this->renderSuccess(compact('list'));

    }


    /*
     * 师傅添加线下订单
     */
    public function addOfflineOrder()
    {
        $data = input();

        $orderModel = new AppointmentOrderModel();

        $status = $orderModel->addOffline($data);

        if ($status) return $this->renderSuccess([], 'success');

        return $this->renderError($orderModel->getError());

    }

    /*
     * 师傅自建单，获取可选择的下级服务人员
     */
    public function serviceSon()
    {
        $id = input('id');

        if(!$id){
            return $this->renderError('id必传');
        }

        $order = AppointmentOrderModel::get(['id'=>$id,'service_id'=>$this->user['user_id']]);

        if(!$order){
            return $this->renderError('参数错误');
        }

        $type_id = $order['type_id'];
        $date_time = $order['appointment_date'];
        $time_id = $order['time_id'];
        $where = [
            'is_delete' => 0,
        ];
        $time_arr = explode(',',$time_id);
        $sub_arr =[];
        $ar = [];
        foreach ($time_arr as $val){
            $ids = AppointmentOrderModel::where("appointment_date", $date_time)
                ->where('find_in_set(:time_id,time_id)',['time_id'=>$val])
                ->where("status", 'in', [1, 2])
                ->where($where)
                ->column('service_id');

            $sub_arr = array_merge($sub_arr, $ids);
        }
        $sub_arr = array_unique($sub_arr);

        $server_pid =  Db::name('server_user')->where(['user_id'=>$order['service_id']])->value('pid');
        if(empty($server_pid)){
            return $this->renderSuccess([], 'success');
        }

        $not_in = Db::name('server_user')->where(['pid'=>['NEQ',$server_pid]])->column('user_id');

        $ar = array_merge($ar, $sub_arr);

        $ar = array_merge($ar, $not_in);

        $all_server_man = \app\common\model\server\User::allServer($type_id, $ar);

        return $this->renderSuccess($all_server_man, 'success');
    }

    /*
     * 提交自建单
     */
    public function takeServerSon()
    {
        $id = input('id');
        $user_id = input('user_id');
        $user_name = input('user_name');

        if(!$id){
            return $this->renderError('id必传');
        }
        if(!$user_id){
            return $this->renderError('user_id必传');
        }
        if(!$user_name){
            return $this->renderError('user_name必传');
        }

        $check = \app\common\model\server\User::get(['user_id'=>$user_id]);

        if(!$check){
            return $this->renderError('服务人员不存在');
        }

        $order = AppointmentOrderModel::get(['id'=>$id,'service_id'=>$this->user['user_id']]);

        if(!$order){
            return $this->renderError('参数错误');
        }


        $order->is_rec = 1;
        $order->p_service_id = $order['service_id'];
        $order->p_service_name = $order['service_name'];
        $order->service_id = $user_id;
        $order->service_name = $user_name;
        $order->save();


        /*$infos = Db::name('appointment_service')->where('order_id', $id)->find();
        $ao = Db::name('appointment_order')->where('id',$infos['order_id'])->find();
        if($ao['p_service_id']>0){
            Db::name('appointment_service')->insert([
                'order_id' => $infos['order_id'],
                'service_id' => $ao['service_id'],
                'confirm_time' => $infos['confirm_time'],
                'is_start' => $infos['is_start'],
                'start_time' => $infos['start_time'],
                'end_time' => $infos['end_time'],
                'use_time' => $infos['use_time'],
                'price' => $infos['price'],
                'service_price' => $infos['service_price'],
                'real_price' => abs($infos['service_price']-$infos['real_price']),
                'remark' => $infos['remark'],
                'status' => $infos['status'],
                'pay_status' => $infos['pay_status'],
                'is_delete' => $infos['is_delete'],
                'wxapp_id' => $infos['wxapp_id'],
                'create_time' => time(),
                'update_time' => 0,
                'pay_time' => $infos['pay_time'],
                'is_show' => $infos['is_show'],
                'server_num' => $infos['server_num'],
            ]);
        }*/

        return $this->renderSuccess([], 'success');
    }

    /*
     * 获取线下订单支付状态
     */
    public function getOfflinePayStatus()
    {
        $id = input('id');

        if(!$id){
            return $this->renderError('参数错误');
        }
        $appointmentModel = AppointmentOrder::get(['id'=>$id]);

        if(!$appointmentModel){
            return $this->renderError('订单不存在');
        }

        if($appointmentModel['offline_pay_status'] == 1){
            return $this->renderSuccess(['status'=>1], 'success');
        }else{
            return $this->renderSuccess(['status'=>0], 'success');
        }
    }
    /*
     * YPP 拨打电话日志
     */
    public function makephonecall()
    {
        $id = input('id');
        AppointmentRecord::addRecord($id,'',7);
        return $this->renderSuccess(['status'=>1], 'success');
    }

}
